import { _decorator, Component, Node ,Event, UITransform, Vec3, Prefab, instantiate, director, Collider2D, IPhysics2DContact, Contact2DType, RigidBody2D} from 'cc';
import { TabEnum } from '../enum';
import { enemyContral } from './enemyContral';
const { ccclass, property } = _decorator;

@ccclass('playerControls')
export class playerControls extends Component {

    @property(Node)
    canvas: Node = null;

    @property(Prefab)
    bulletPrefab: Prefab | null = null;

    rightBody:RigidBody2D |null = null;
    start() {
        //移动
        this.node.on(Node.EventType.TOUCH_MOVE, (event)=>{
            // console.log('event :>> ', event.getUILocation(),this.node);
            // this.node.setPosition(event.getUILocation())
            const touchPos = event.getUILocation();
            // 将触摸点坐标转换为节点坐标系  转换为游戏世界中的实际位置（节点坐标）
            const pos = this.node.parent.getComponent(UITransform)
            .convertToNodeSpaceAR(new Vec3(touchPos.x, touchPos.y, 0));
            // 设置节点位置
            this.node.setPosition(pos);
        });
        // 攻击
        this.schedule(()=>{
            if (this.bulletPrefab) {
                // 实例化子弹预制体
                let bullet = instantiate(this.bulletPrefab);
                // 将子弹添加到场景中
                let bulletHeight = bullet.getComponent(UITransform)
                bullet.setParent(this.canvas);
                // 设置子弹初始位置（在飞机上方）
                const pos = this.node.position;
                bullet.setPosition(new Vec3(pos.x, pos.y + bulletHeight.height+63, 0));
            }
        },0.5)
       
        //监听碰撞
        const collider = this.getComponent(Collider2D);
        if(collider){
        collider.on(Contact2DType.BEGIN_CONTACT,this.onBeginContact,this)

        }
    }
 
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D,
         contact: IPhysics2DContact | null) {
        console.log('碰撞开始：英雄',otherCollider.tag);
        if(otherCollider.tag == TabEnum.ENEMY){
            // director.loadScene('gameOver')
            //销毁自身
            this.node.destroy()
            //销毁敌机
            otherCollider.node.getComponent(enemyContral).die()

        }
    }
    update(deltaTime: number) {
         // 如果需要在update中同步位置
       
    }
}


